package com.hyjiacan.tools.utils

import java.io.UnsupportedEncodingException
import java.security.InvalidKeyException
import java.security.KeyFactory
import java.security.KeyPairGenerator
import java.security.NoSuchAlgorithmException
import java.security.interfaces.RSAPrivateKey
import java.security.spec.InvalidKeySpecException
import java.security.spec.PKCS8EncodedKeySpec
import java.util.*
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.NoSuchPaddingException

object Rsa {
    private var privateKey: String? = null
    var publicKey: String? = null

    @Throws(
        UnsupportedEncodingException::class,
        NoSuchAlgorithmException::class,
        NoSuchPaddingException::class,
        InvalidKeyException::class,
        IllegalBlockSizeException::class,
        BadPaddingException::class,
        InvalidKeySpecException::class
    )
    fun decrypt(data: String?): String {
        val decoder = Base64.getDecoder()
        //64位解码加密后的字符串
        val inputByte = decoder.decode(data!!.toByteArray())
        //base64编码的私钥
        val decoded = decoder.decode(privateKey)
        val kf = KeyFactory.getInstance("RSA")
        val keySpec = PKCS8EncodedKeySpec(decoded)
        val priKey = kf.generatePrivate(keySpec) as RSAPrivateKey
        //RSA解密
        val cipher = Cipher.getInstance("RSA")
        cipher.init(Cipher.DECRYPT_MODE, priKey)
        return String(cipher.doFinal(inputByte))
    }

    @Throws(NoSuchAlgorithmException::class)
    fun makeKeys() {
        if (publicKey != null && "" != publicKey) {
            return
        }
        //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        val keyPairGen = KeyPairGenerator.getInstance("RSA")
        keyPairGen.initialize(4096)
        //通过对象 KeyPairGenerator 获取对象KeyPair
        val keyPair = keyPairGen.generateKeyPair()
        val encoder = Base64.getEncoder()
        privateKey = encoder.encodeToString(keyPair.private.encoded)
        publicKey = encoder.encodeToString(keyPair.public.encoded)
    }
}